<template>
  <Modal v-model:visible="showModal" title="航空-客运信息" width="1300px">
    <div class="flex flex-col w-full">
      <a-tabs v-model:activeKey="activeKey" size="small">
        <a-tab-pane key="1" tab="基本信息"></a-tab-pane>
        <a-tab-pane key="2" tab="客座率"></a-tab-pane>
      </a-tabs>

      <div class="flex flex-row items-center mb-1">
        <a-select
          v-model:value="searchParams.year"
          :options="utils.genSelectOptions('year')"
          @change="loadData"
        ></a-select>
        <a-select
          v-if="activeKey === '2'"
          class="ml-2"
          size="small"
          v-model:value="month"
          :options="utils.genSelectOptions('month')"
          @change="loadDataByChart"
        ></a-select>
      </div>

      <div v-show="activeKey === '1'">
        <vxe-table
          :loading="true"
          v-bind="customTableStyle"
          :data="tableData"
          class="custom-vxe-table"
        >
          <vxe-column field="year" title="年份" width="80">
            <template #default="{ row }"> {{ row.year }}年 </template>
          </vxe-column>
          <vxe-column field="month" title="月份" width="80" :sortable="true">
            <template #default="{ row }"> {{ row.month }}月 </template>
          </vxe-column>
          <vxe-column field="totalFlights" title="总架次" minWidth="100" :sortable="true">
            <template #default="{ row }"> {{ row.totalFlights }}架次 </template>
          </vxe-column>
          <vxe-column field="passengerTotal" title="旅客总量" minWidth="100" :sortable="true">
            <template #default="{ row }"> {{ row.passengerTotal }}人 </template>
          </vxe-column>
          <vxe-column field="arrivalNum" title="进港人数" minWidth="100" :sortable="true">
            <template #default="{ row }"> {{ row.arrivalNum }}人 </template>
          </vxe-column>
          <vxe-column
            field="arrivalPassengerLoad"
            title="进港客座率"
            minWidth="100"
            :sortable="true"
          >
            <template #default="{ row }"> {{ row.arrivalPassengerLoad * 100 }}% </template>
          </vxe-column>
          <vxe-column field="departureNum" title="出港人数" minWidth="100" :sortable="true">
            <template #default="{ row }"> {{ row.departureNum }}人 </template>
          </vxe-column>
          <vxe-column
            field="departurePassengerLoad"
            title="出港客座率"
            minWidth="100"
            :sortable="true"
          >
            <template #default="{ row }"> {{ row.departurePassengerLoad * 100 }}% </template>
          </vxe-column>
          <vxe-column
            field="withinPassengerNum"
            title="疆内旅客人数"
            minWidth="120"
            :sortable="true"
          >
            <template #default="{ row }"> {{ row.withinPassengerNum }}人 </template>
          </vxe-column>
          <vxe-column
            field="withinPassengerLoad"
            title="疆内客座率"
            minWidth="100"
            :sortable="true"
          >
            <template #default="{ row }"> {{ row.withinPassengerLoad * 100 }}% </template>
          </vxe-column>
          <vxe-column
            field="outsidePassengerNum"
            title="疆外旅客人数"
            minWidth="120"
            :sortable="true"
          >
            <template #default="{ row }"> {{ row.outsidePassengerNum }}人 </template>
          </vxe-column>
          <vxe-column
            field="outsidePassengerLoad"
            title="疆外客座率"
            minWidth="100"
            :sortable="true"
          >
            <template #default="{ row }"> {{ row.outsidePassengerLoad * 100 }}% </template>
          </vxe-column>
        </vxe-table>
      </div>

      <div v-if="activeKey === '2'" class="w-[800px] flex flex-col mx-auto px-4 h-[50vh]">
        <div class="flex flex-row flex-1 h-full">
          <div class="w-[300px] h-full flex-1 flex flex-col">
            <p class="text-sm text-gray-400 mb-[0px] text-center">进港客座率</p>
            <div id="jgkzlChart" class="w-full flex-1"></div>
          </div>
          <div class="w-[300px] flex-1 flex flex-col">
            <p class="text -sm text-gray-400 mb-[0px] text-center">出港客座率</p>
            <div id="cgkzlChart" class="w-full flex-1"></div>
          </div>
        </div>

        <div class="flex flex-row flex-1">
          <div class="w-[300px] flex-1 flex flex-col">
            <p class="text-sm text-gray-400 mb-[0px] text-center">疆内客座率</p>
            <div id="jnkzlChart" class="w-full flex-1"></div>
          </div>
          <div class="w-[300px] flex-1 flex flex-col">
            <p class="text-sm text-gray-400 mb-[0px] text-center">疆外客座率</p>
            <div id="jwkzlChart" class="w-full flex-1"></div>
          </div>
        </div>
      </div>
    </div>
  </Modal>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'

import Modal from '@/components/modal.vue'
import { Apis } from '@/api'
import { message } from 'ant-design-vue'
import * as utils from '../../utils'
import * as echarts from 'echarts'

const activeKey = ref('1')
const month = ref('12')

const isLoading = ref(false)

const showModal = ref(false)

const searchParams = ref({
  year: '',
})
const tableData = ref<any[]>([])

watch(
  () => activeKey.value,
  (newVal) => {
    if (newVal == '2') {
      nextTick(() => {
        initJgkzlByOptionsChart()
        initCgkzlByOptionsChart()
        initJnkzlByOptionsChart()
        initJwkzlByOptionsChart()
      })
    }
  },
)

// 统一管理表格样式
const customTableStyle = {
  ...utils.customTableStyle,
  footerMethod: ({ columns, data }) => {
    const footerData = [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return '合计'
        }

        if (['totalFlights'].includes(column.field)) {
          return (utils.sumNum(data, column.field) || '') + '架次'
        }

        if (
          [
            'passengerTotal',
            'arrivalNum',
            'departureNum',
            'withinPassengerNum',
            'outsidePassengerNum',
          ].includes(column.field)
        ) {
          return (utils.sumNum(data, column.field) || '') + '人'
        }

        return ''
      }),
    ]
    return footerData
  },
}

function loadData() {
  isLoading.value = true

  Apis.szbt.aviation
    .get_list({
      params: {
        year: searchParams.value.year,
      },
    })
    .then((res) => {
      tableData.value = (res.rows || [])
        .filter((item) => item.year == searchParams.value.year)
        .sort((a: any, b: any) => {
          // 先按年份倒序
          if (b.month !== a.month) {
            return a.month - b.month
          }
        })
        .map((item: any, index: number) => {
          item.index = index + 1
          return item
        })

      setTimeout(() => {
        loadDataByChart()

        if (!timer) {
          timer = setInterval(() => {
            drawChart()
          }, 100)
        }
      }, 300)

      // const totalPassengerCount = tableData.value.reduce((sum, item) => sum + (item.passengerVolume || 0), 0);
      // tableData.value = tableData.value.map(item => {
      //   const passengerCount = item.passengerVolume || 0;
      //   item.passengerCountPercentage = totalPassengerCount ? ((passengerCount / totalPassengerCount) * 100).toFixed(2) : 0;
      //   return item;
      // });
    })
    .catch((err) => {
      message.error('获取数据失败')
    })
    .finally(() => {
      isLoading.value = false
    })
}

/** 进港客座率 */
const jgkzlChartByOptions = reactive({})

/** 出港客座率 */
const cgkzlChartByOptions = reactive({})

/** 疆内客座率 */
const jnkzlChartByOptions = reactive({})

/** 疆外客座率 */
const jwkzlChartByOptions = reactive({})

/** 进港客座率 */
function initJgkzlByOptionsChart() {
  const chartDom = document.getElementById('jgkzlChart')
  if (!chartDom) return
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }
  myChart.setOption(jgkzlChartByOptions, { notMerge: true })
}

/** 出港客座率 */
function initCgkzlByOptionsChart() {
  const chartDom = document.getElementById('cgkzlChart')
  if (!chartDom) {
    return
  }
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }
  myChart.setOption(cgkzlChartByOptions, { notMerge: true })
}

/** 疆内客座率 */
function initJnkzlByOptionsChart() {
  const chartDom = document.getElementById('jnkzlChart')
  if (!chartDom) return
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }
  myChart.setOption(jnkzlChartByOptions, { notMerge: true })
}

/** 疆外客座率 */
function initJwkzlByOptionsChart() {
  const chartDom = document.getElementById('jwkzlChart')
  if (!chartDom) return
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }
  myChart.setOption(jwkzlChartByOptions, { notMerge: true })
}

async function loadDataByChart() {
  try {
    const { year } = searchParams.value

    const monthInfo = tableData.value.find((item) => item.month == month.value) || {}

    Object.assign(jgkzlChartByOptions, initKzlChart(monthInfo.arrivalPassengerLoad || 0))
    Object.assign(cgkzlChartByOptions, initKzlChart(monthInfo.departurePassengerLoad || 0))
    Object.assign(jnkzlChartByOptions, initKzlChart(monthInfo.withinPassengerLoad || 0))
    Object.assign(jwkzlChartByOptions, initKzlChart(monthInfo.outsidePassengerLoad || 0))

    initJgkzlByOptionsChart()
    initCgkzlByOptionsChart()
    initJnkzlByOptionsChart()
    initJwkzlByOptionsChart()
  } catch (error) {}
}

let angle = 0 //角度，用来做简单的动画效果的

//获取圆上面某点的坐标(x0,y0表示坐标，r半径，angle角度)
function getCirlPoint(x0, y0, r, angle) {
  const x1 = x0 + r * Math.cos((angle * Math.PI) / 180)
  const y1 = y0 + r * Math.sin((angle * Math.PI) / 180)
  return {
    x: x1,
    y: y1,
  }
}

/** 生成客座率图表 */
function initKzlChart(value: number) {
  value = value * 100
  return {
    title: {
      text: '{a|' + value + '}{c|%}',
      x: 'center',
      y: 'center',
      textStyle: {
        rich: {
          a: {
            fontSize: 14,
            // color: '#ffffff',
          },

          c: {
            fontSize: 12,
            // color: '#ffffff',
            // padding: [5,0]
          },
        },
      },
    },
    series: [
      {
        name: 'ring5',
        type: 'custom',
        coordinateSystem: 'none',
        renderItem: function (params, api) {
          return {
            type: 'arc',
            shape: {
              cx: api.getWidth() / 2,
              cy: api.getHeight() / 2,
              r: (Math.min(api.getWidth(), api.getHeight()) / 2) * 0.6,
              startAngle: ((0 + angle) * Math.PI) / 180,
              endAngle: ((90 + angle) * Math.PI) / 180,
            },
            style: {
              stroke: '#0CD3DB',
              fill: 'transparent',
              lineWidth: 1.5,
            },
            silent: true,
          }
        },
        data: [0],
      },
      {
        name: 'ring5',
        type: 'custom',
        coordinateSystem: 'none',
        renderItem: function (params, api) {
          return {
            type: 'arc',
            shape: {
              cx: api.getWidth() / 2,
              cy: api.getHeight() / 2,
              r: (Math.min(api.getWidth(), api.getHeight()) / 2) * 0.6,
              startAngle: ((180 + angle) * Math.PI) / 180,
              endAngle: ((270 + angle) * Math.PI) / 180,
            },
            style: {
              stroke: '#0CD3DB',
              fill: 'transparent',
              lineWidth: 1.5,
            },
            silent: true,
          }
        },
        data: [0],
      },
      {
        name: 'ring5',
        type: 'custom',
        coordinateSystem: 'none',
        renderItem: function (params, api) {
          return {
            type: 'arc',
            shape: {
              cx: api.getWidth() / 2,
              cy: api.getHeight() / 2,
              r: (Math.min(api.getWidth(), api.getHeight()) / 2) * 0.65,
              startAngle: ((270 + -angle) * Math.PI) / 180,
              endAngle: ((40 + -angle) * Math.PI) / 180,
            },
            style: {
              stroke: '#0CD3DB',
              fill: 'transparent',
              lineWidth: 1.5,
            },
            silent: true,
          }
        },
        data: [0],
      },
      {
        name: 'ring5',
        type: 'custom',
        coordinateSystem: 'none',
        renderItem: function (params, api) {
          return {
            type: 'arc',
            shape: {
              cx: api.getWidth() / 2,
              cy: api.getHeight() / 2,
              r: (Math.min(api.getWidth(), api.getHeight()) / 2) * 0.65,
              startAngle: ((90 + -angle) * Math.PI) / 180,
              endAngle: ((220 + -angle) * Math.PI) / 180,
            },
            style: {
              stroke: '#0CD3DB',
              fill: 'transparent',
              lineWidth: 1.5,
            },
            silent: true,
          }
        },
        data: [0],
      },
      {
        name: 'ring5',
        type: 'custom',
        coordinateSystem: 'none',
        renderItem: function (params, api) {
          const x0 = api.getWidth() / 2
          const y0 = api.getHeight() / 2
          const r = (Math.min(api.getWidth(), api.getHeight()) / 2) * 0.65
          const point = getCirlPoint(x0, y0, r, 90 + -angle)
          return {
            type: 'circle',
            shape: {
              cx: point.x,
              cy: point.y,
              r: 4,
            },
            style: {
              stroke: '#0CD3DB', //粉
              fill: '#0CD3DB',
            },
            silent: true,
          }
        },
        data: [0],
      },
      {
        name: 'ring5', //绿点
        type: 'custom',
        coordinateSystem: 'none',
        renderItem: function (params, api) {
          const x0 = api.getWidth() / 2
          const y0 = api.getHeight() / 2
          const r = (Math.min(api.getWidth(), api.getHeight()) / 2) * 0.65
          const point = getCirlPoint(x0, y0, r, 270 + -angle)
          return {
            type: 'circle',
            shape: {
              cx: point.x,
              cy: point.y,
              r: 4,
            },
            style: {
              stroke: '#0CD3DB', //绿
              fill: '#0CD3DB',
            },
            silent: true,
          }
        },
        data: [0],
      },
      {
        type: 'pie',
        radius: ['58%', '45%'],
        silent: true,
        clockwise: true,
        startAngle: 90,
        z: 0,
        zlevel: 0,
        label: {
          normal: {
            position: 'center',
          },
        },
        data: [
          {
            value: value,
            name: '',
            itemStyle: {
              normal: {
                color: {
                  // 完成的圆环的颜色
                  colorStops: [
                    {
                      offset: 0,
                      color: '#4FADFD', // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: '#28E8FA', // 100% 处的颜色
                    },
                  ],
                },
              },
            },
          },
          {
            value: 100 - value,
            name: '',
            label: {
              normal: {
                show: false,
              },
            },
            itemStyle: {
              normal: {
                color: '#173164',
              },
            },
          },
        ],
      },

      {
        name: '',
        type: 'gauge',
        radius: '58%',
        center: ['50%', '50%'],
        startAngle: 0,
        endAngle: 359.9,
        splitNumber: 8,
        hoverAnimation: true,
        axisTick: {
          show: false,
        },
        splitLine: {
          length: 60,
          lineStyle: {
            width: 5,
            color: '#061740',
          },
        },
        axisLabel: {
          show: false,
        },
        pointer: {
          show: false,
        },
        axisLine: {
          lineStyle: {
            opacity: 0,
          },
        },
        detail: {
          show: false,
        },
        data: [
          {
            value: 0,
            name: '',
          },
        ],
      },
    ],
  }
}

function drawChart() {
  angle = angle + 3
  initJgkzlByOptionsChart()
  initCgkzlByOptionsChart()
  initJnkzlByOptionsChart()
  initJwkzlByOptionsChart()
}

let timer = null

onMounted(() => {})

onUnmounted(() => {
  clearInterval(timer)
})

defineExpose({
  setData: (data: any) => {
    const { params } = data
    searchParams.value = params
    // tableData.value = data;
  },
  open: () => {
    showModal.value = true
    loadData()
  },
})
</script>

<style lang="scss" src="@/styles/custom-vxe-table.scss"></style>
